package com.sky.handler;

import com.sky.constant.MessageConstant;
import com.sky.exception.BaseException;
import com.sky.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(value = DataAccessException.class)
    @ResponseBody
    public Result sqlException(SQLIntegrityConstraintViolationException ex){
        log.error("sql异常信息:{}",ex.getMessage());
        String message=ex.getMessage();
        if (ex.getMessage().contains("Duplicate entry")) {
            String[] arr = message.split("");
            String username = arr[2];
            return Result.error(username + MessageConstant.ALREADY_EXISTS);
        }return Result.error(MessageConstant.UNKNOWN_ERROR);
    }


    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler(BaseException.class)
    public Result baseExceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    @ExceptionHandler(RuntimeException.class)
    public Result runtimeExceptionHandler(RuntimeException ex){
        log.error("运行异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public Result exceptionHandler(Exception ex){
        log.error("未知异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

}
